﻿var isDocked;
var fulltimer;
var halftimer;
var endtimer;
var statstimer;
function view_onOpen(){
	//Set default values
	options.putDefaultValue("minutes",30);
	options.putDefaultValue("play",true);
	options.putDefaultValue("Opacity", 100);
	//Transparency
  setOpacity(options.getValue("Opacity"));
	plugin.onAddCustomMenuItems = AddCustomMenuItems;
	//Start to count
	setFullTimer();
}
function statsTimer(){
	//Update the timeleft
	var left=parseInt(timeleft.innerText)-1;
	if (left!=1){
		minuteslabel.innerText=MINUTES;
	}else{
		minuteslabel.innerText=MINUTE;
	}
	timeleft.innerText=left;
	view.caption=NEXT_GULP+" "+left+" "+minuteslabel.innerText+" - "+GADGET_NAME;
}
function setFullTimer(){
	//Setup the stats timer
	clearTimers();
	timeleft.innerText=options.getValue("minutes")+1;
	statsTimer();
	statstimer=view.setInterval(statsTimer,60000); //every minute
	//Setup the first timer
	fulltimer=view.setTimeout(setHalfTimer,(options.getValue("minutes")*60000/3));
	status.src="stock_images/blue.png";
}
function setHalfTimer(){
	fulltimer=view.setTimeout(setEndTimer,(options.getValue("minutes")*60000/3));
	status.src="stock_images/yellow.png";
}
function setEndTimer(){
	fulltimer=view.setTimeout(setTimeOut,(options.getValue("minutes")*60000/3));
	status.src="stock_images/red.png";
}
function setTimeOut(){
	//Play sound (if desired)
	if (options.getValue("play")){
		playSound();
	}
	showNotifier("titulo","texto");
	//Start over (will clear timers)
	setFullTimer();
}
function clearTimers(){
	//Clear the timers
 try{
  view.clearTimeout(fulltimer);
  view.clearTimeout(halftimer);
  view.clearTimeout(endtimer);
  view.clearInterval(statstimer);
 }catch(e){
	//
 }
}
function view_OnDock(){
	isDocked=true;
	timeleft.x=-14;
	timeleft.y=43;
	timeleft.size=15;
	view.width=100;
	bkg.visible=false;
}
function view_onUnDock(){
	isDocked=false;
	timeleft.x=105;
	timeleft.y=20;
	timeleft.size=20;
	view.width=250;
	bkg.visible=true;
}
/** Transparency **/
function AddCustomMenuItems(menu) {
  var opacSub = menu.AddPopup(TRANSP_LABEL);
  for (var i=100; i>10; i-=10) {
    var capt = i+"%";
    opacSub.AddItem(capt, (getOpacity()==i)?gddMenuItemFlagChecked:0, onOpacClicked);
  }
	menu.AddItem(DRINKED, 0, setFullTimer);
}
function onOpacClicked(itemText) {
    var opac = itemText.substring(0, itemText.indexOf("%"));
    setOpacity(parseInt(opac));
		options.putValue("Opacity", opac);
}
function setOpacity(opac) {
  view_holder.opacity = (255/100)*opac;
}
function getOpacity() {
  var opac = view_holder.opacity/(255/100);
  opac = Math.round(opac);
  return opac;
}